


function ajax(url, type, data = {}) {

    let params = '';
    // 遍历data
    for (let key in data) {
        params += `${key}=${data[key]}&`;
    }
    params = params.substring(0, params.length - 1);


    const p = new Promise((resolve, reject) => {
        // 异步的程序
        const xhr = new XMLHttpRequest();

        // 判断请求的方式
        if(type.toLowerCase() === 'get') {
            xhr.open(type, url + '?' + params , true);
            xhr.send();
        }
        else if(type.toLowerCase() === 'post') {
            xhr.open(type , url , true) ;
            xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded') ;
            xhr.send(params) ;
        }


        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // resolve('成功啦') ;
                let data = xhr.responseText;
                try{
                    data = JSON.parse(data) ;
                } catch(err) {
                    console.log(err);
                }
                resolve(data);
            }
        }
    });

    return p
}


